<?php

namespace App\Http\Controllers\Api;

use App\Model\Cart;
use App\Model\Orders;
use App\Model\OrdersInfo;
use App\Model\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use EasyWeChat\Factory;

class PayController extends Controller
{
    //购物车创建支付订单
    public function creatCartPay(Request $request){
        $user_id = $request->input("userId");
        $cart_id = $request->input("cartId");
        $total = $request->input("total");
        $remark = $request->input("remark");
        $orders = new Orders();
        $cart = new Cart();
        if(empty($user_id) || empty($cart_id) ||empty($total)){
            $this->error('参数错误！');
        }
        $cartId = explode(',',$cart_id);
        $orders->orders_num = $this->build_order_no();
        $orders->user_id = $user_id;
        $orders->real_price = $total;
        $orders->remark = $remark;
        $res = $orders->save();
        $ordersId = $orders->id;
        $orders_num = $orders->orders_num;
        if($res){
            foreach ($cartId as $k=>$v){
                if(!empty($v)){
                    $cartInfo = $cart->find($v);
                    $ordersInfo = new OrdersInfo();
                    $ordersInfo->orders_id = $ordersId;
                    $ordersInfo->goods_id = $cartInfo['goods_id'];
                    $ordersInfo->num = $cartInfo['num'];
                    $result = $ordersInfo->save();
                    $cart->where('id',$v)->delete();
                }
                if(!$result){
                    $this->error('网络错误'.__LINE__);
                }
            }
            $this->success(array('orders_id'=>$ordersId,'orders_num'=>$orders_num));
        }
    }

    //支付
    public function payNow(Request $request){
        $userId = $request->input("userId");
        $ordersId = $request->input("orders_id");
        $orders_num = $request->input("orders_num");
        $user = new User();
        $orders = new Orders();
        if(empty($userId) || empty($ordersId) || empty($orders_num)){
            $this->error('参数错误');
        }
        $openid = $user->find($userId)->openid;
        $price = $orders->find($ordersId)->real_price;
        if(empty($openid) || empty($price)){
            $this->error('网络错误！'.__LINE__);
        }
        $config = [
            'app_id' => 'wx00cae474fadcba6b',
            'secret' => '4cd3027189cda4ec3df408861cf95896',
            'mch_id' => '1487671942',
            'key'    => 'GhXitOme3jCp8U6rGoct2UDEc5gZQGBH',
            'cert_path' => '/apiclient_cert.pem', // XXX: 绝对路径！！！！
            'key_path'  => '/apiclient_key.pem',
            'notify_url' => 'https://www.gengyong.com.cn/pay/notify',

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];
        $product = [
            'trade_type'       => 'JSAPI',
            // 微信公众号支付填JSAPI
            'body'             => '微信支付',
            'detail'           => '在线点餐',
            'out_trade_no'     => $orders_num,
            // 这是自己ERP系统里的订单ID，不重复就行。
//            'total_fee'        => $price*100,
            'total_fee'        => 1,
            // 金额，单位只能是分。
            'notify_url'       => 'https://www.gengyong.com.cn/api/pay/notify',
            // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => $openid,
            // 这个不能少，少了要报错。
        ];
        $app = Factory::payment($config);
        //统一下单获取prepay_id
        $result = $app->order->unify($product);
        if($result['return_code'] != 'SUCCESS' || $result['return_msg'] != 'OK'){
            $this->error('网络错误'.__LINE__);
        }
        //获取调用SDK的配置参数，支付签名、时间戳等信息
        $jssdk = $app->jssdk;
        $data = $jssdk->sdkConfig($result['prepay_id']);
        if(count($data)>0){
            $this->success($data);
        }else{
            $this->error('网络错误');
        }
    }
    /**生成唯一订单号
     *@return int 返回16位的唯一订单号
     */
    public function build_order_no(){
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    public function test(){
        $config = [
            'app_id' => 'wx00cae474fadcba6b',
            'secret' => '4cd3027189cda4ec3df407791cf95896',
            'mch_id' => '1487671942',
            'key'    => 'GhXitOme3jCp8U6rGoct2UDEc5gZQGBH',
            'cert_path' => '/apiclient_cert.pem', // XXX: 绝对路径！！！！
            'key_path'  => '/apiclient_key.pem',
            'notify_url' => 'https://www.gengyong.com.cn/pay/notify',

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];

        $product = [
            'trade_type'       => 'JSAPI',
            // 微信公众号支付填JSAPI
            'body'             => '微信支付',
            'detail'           => '天路本草',
            'out_trade_no'     => time(),
            // 这是自己ERP系统里的订单ID，不重复就行。
            'total_fee'        => 100,
            // 金额，单位只能是分。
            'notify_url'       => 'https://www.gengyong.com.cn/api/pay/notify',
            // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => 'oBWEA5eDzZ-Vz11zD9h4JclYDM2M',
            // 这个不能少，少了要报错。
        ];
        $app = Factory::payment($config);
        $result = $app->order->unify($product);
        $jssdk = $app->jssdk;
        $config = $jssdk->sdkConfig($result['prepay_id']);

        var_dump($config);
    }

    //回调
    public function notify(Request $request){
        $postData = file_get_contents('php://input');
        $xml_array = simplexml_load_string($postData, "SimpleXMLElement", LIBXML_NOCDATA);
        $orders = new Orders();
        $ordersInfo = $orders->where('orders_num',$xml_array->out_trade_no)->first();
        $ordersInfo->pay_num = $xml_array->transaction_id;
        $ordersInfo->status = 1;
        $ordersInfo->pay_time = date('Y-m-d H:i:s');
        $ordersInfo->save();
    }
}
